package com.sxt.sys.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxt.pro.Ny_data.xin.HttpURLConnectionTest;
import com.sxt.pro.pojo.Guide;
import com.sxt.pro.pojo.InclusiveService;
import com.sxt.pro.pojo.LivePay;
import com.sxt.pro.pojo.Person;
import com.sxt.pro.pojo.Product;
import com.sxt.pro.pojo.Screens;
import com.sxt.pro.pojo.ServiceLead;
import com.sxt.pro.pojo.Sources;
import com.sxt.pro.pojo.SurroundDiscount;
import com.sxt.pro.pojo.WaterFall;
import com.sxt.pro.service.GuideService;
import com.sxt.pro.service.InclusiveServiceService;
import com.sxt.pro.service.LivePayService;
import com.sxt.pro.service.PersonService;
import com.sxt.pro.service.ProductService;
import com.sxt.pro.service.ScreensService;
import com.sxt.pro.service.ServiceLeadService;
import com.sxt.pro.service.SourcesService;
import com.sxt.pro.service.SurroundDiscountService;
import com.sxt.pro.service.WaterFallService;
import com.sxt.sys.common.ResultObj;
import com.sxt.sys.domain.Terminal;
import com.sxt.sys.service.TerminalService;

import net.sf.json.JSONObject;
import utils.ResponseWrapper;

@Controller
@RequestMapping("sys")
public class SystemController {
	//设备终端
	@Autowired
	private TerminalService terminalService;
	//产品
	@Autowired
	private ProductService productService;
	//瀑布流控制
	@Autowired
	private WaterFallService waterFallService;
	//员工
	@Autowired
	private PersonService personService;
	//网点导览
	@Autowired
	private GuideService guideService;
	//素材
	@Autowired
	private SourcesService sourcesService;
	// websockegt 发送消息模板 =
	@Autowired
	private SimpMessagingTemplate template;
	//普惠业务
	@Autowired
	private InclusiveServiceService inclusiveServiceService;
	// 业务引导
	@Autowired
	private ServiceLeadService serviceLeadService;
	//生活缴费
	@Autowired
	private LivePayService livePayService;
	//周边优惠
	@Autowired
	private SurroundDiscountService surroundDiscountService;
	//屏保
	@Autowired
	private ScreensService  screensService;
	
	/**
	 * 根据设备ip,查看网点编号：远程视频权限控制
	 */
	@RequestMapping("/loadNetworkByterminalNo")
	@ResponseBody
	public ResponseWrapper loadNetworkByterminalNo(String terminal_no){
		QueryWrapper<Terminal> queryWrapper=new QueryWrapper<>();
		try {
			queryWrapper.eq(StringUtils.isNotBlank(terminal_no), "terminal_no", terminal_no);
			Terminal terminal = this.terminalService.getOne(queryWrapper);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("networkid", terminal.getNetworkid());
			map.put("terminaltime", terminal.getTerminaltime());
			return ResponseWrapper.markSuccess(map);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseWrapper.markParamError();
		}
		
	}
	
	/**
	 * 根据年龄、性别、设备编号推送产品
	 * @param age
	 * @param 
	 * @return
	 */
	@RequestMapping("/sendProduct")
	@ResponseBody
	public ResponseWrapper sendProduct(String age, String sex ,String terminalNo){
		try {
			 List<Product> products= this.productService.sendProduct(age, sex ,terminalNo);
			 return ResponseWrapper.markSuccess(products);
		} catch (Exception e) {
			e.printStackTrace();
			return  ResponseWrapper.markParamError();
		}
	}
	
	/**
	 * 普通客户推送默认产品
	 * @param age
	 * @param customerLever
	 * @return
	 */
//	@RequestMapping("/sendNormalProduct")
//	@ResponseBody
//	public ResponseWrapper sendNormalProduct(String generalCustomer){
//		try {
//			 List<Product> products= this.productService.sendNormalProduct(generalCustomer);
//			 return ResponseWrapper.markSuccess(products);
//		} catch (Exception e) {
//			e.printStackTrace();
//			return  ResponseWrapper.markParamError();
//		}
//	}
	
	
	/**
	 *@Decription : 互动营销：根据 设备编号 来获取 营销数据
	 * @param terminal_no 设备编号
	 * @return
	 */
	@RequestMapping("/sendProductData")
	@ResponseBody
	public ResponseWrapper sendProductData(String terminal_no){
		try {
		     List<WaterFall>  productData= this.waterFallService.sendProductData(terminal_no);
			 return ResponseWrapper.markSuccess(productData);
		} catch (Exception e) {
			e.printStackTrace();
			return  ResponseWrapper.markParamError();
		}
	}

	
	/**
	 *@Decription : 根据设备编号 获取 员工列表
	 * @param terminal_no  设备编号
	 * @return
	 */
	@RequestMapping("/sendPersonData")
	@ResponseBody
	public ResponseWrapper sendPersonData(String terminal_no){
		try {
		     List<Person>  productData= this.personService.listByterminal(terminal_no);
			 return ResponseWrapper.markSuccess(productData);
		} catch (Exception e) {
			e.printStackTrace();
			return  ResponseWrapper.markParamError();
		}
	}

	
	/**
	 * @Decription : 根据设备编号 获取 网点导览地图
	 * @param terminal_no  设备编号
	 * @return
	 */
	@RequestMapping("/sendGuideData")
	@ResponseBody
	public ResponseWrapper sendGuideData(String terminal_no){
		try {
		     List<Guide>  guideData= this.guideService.listguideByterminal(terminal_no);
			 return ResponseWrapper.markSuccess(guideData);
		} catch (Exception e) {
			e.printStackTrace();
			return  ResponseWrapper.markParamError();
		}
	}
	
	/**
	 *  @Decription : 青岛：文化剧场   第一次前端主动调，随机推送已经审批的素材至前端
	 * @return
	 */
	@RequestMapping("/sendCultureData")
	@ResponseBody
	public ResponseWrapper  sendCultureData(String terminal_no) {
		int available = 1;  //默认发送已经审核的标签
//		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		try {
			 //随机获取5条素材
		     List<Sources>  sourcesData= this.sourcesService.sendSourcesDataByter(terminal_no,available);
//	         Map<String, Object> map = new HashMap<String, Object>();
//	         map.put("sources", sourcesData);
//	         data.add(map);
	         return ResponseWrapper.markSuccess(sourcesData);
		} catch (Exception e) {
			 e.printStackTrace();
			 return  ResponseWrapper.markParamError();
		}
	}
	
	/**
	 * 发送通知信息
	 * @return
	 */
	@RequestMapping("/sendNoticeMessage")
	@ResponseBody
	public String  sendNoticeMessage() {
		List<Map<String, Object>> data = null;
		int available = 1;  //默认已审批
		Date nowTime = null;
		Date beginTime = null;
		Date endTime = null;
		List<Sources>  sourcesDataNew= new ArrayList<Sources>();
		try {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			//获取当前时间
			String newDate = sdf.format(new Date());
			//转化为data模式
			nowTime = sdf.parse(newDate);
			 //获取文化剧场已经审批的素材图片和视频素材
			 QueryWrapper<Sources> queryWrapper = new QueryWrapper<Sources>();
			//筛选条件：网点编号
			  queryWrapper.eq("available",available);
		     List<Sources>  sourcesData= this.sourcesService.list(queryWrapper);
		     for (int i = 0; i < sourcesData.size(); i++) {
		    	if (sourcesData.get(i).getTimerange()!=null  ) {
		    		String beginTime1 = sourcesData.get(i).getTimerange().substring(0, sourcesData.get(i).getTimerange().indexOf("~"));
		    		String endTime1 = sourcesData.get(i).getTimerange().substring(sourcesData.get(i).getTimerange().indexOf("~")+1);
		    		beginTime=sdf.parse(beginTime1);
		    		endTime=sdf.parse(endTime1);
		    		Boolean flag = belongCalendar(nowTime, beginTime, endTime);
				  if (flag) {
					  sourcesDataNew.add(sourcesData.get(i));
				  }				
				}
			}
	         Map<String, Object> map = new HashMap<String, Object>();
	         data = new ArrayList<Map<String, Object>>();
	         if (!sourcesDataNew.isEmpty()) {
	        	 map.put("sources", sourcesDataNew);
	        	  data.add(map);
	        	  return  JSON.toJSONString(data);
//	        	 template.convertAndSend("/topic/service_Notice",new OutMessage(JSON.toJSONString(data)));
			}
		} catch (Exception e) {
			 e.printStackTrace();
		}
		return "没有"; 
	}
	

	
	/**
	 *  @Decription : 爬取银行数据
	 * @return
	 */
	@RequestMapping("/sendBankData")
	@ResponseBody
	public JSONObject  sendBnakData() {
		try {
			String bankData = HttpURLConnectionTest.httpURLConectionGET();
			JSONObject json = JSONObject.fromObject(bankData);
//	         return ResponseWrapper.markSuccess(json);
	         return json;
		} catch (Exception e) {
			 e.printStackTrace();
			 return  null;
		}
	}
	
	
	/**
	 * @Decription : 模板播放模式选择
	 * @return
	 */
	@RequestMapping("/sendModelData")
	@ResponseBody
	public ResultObj  sendModelData(@RequestParam Map<String, String> params ) {
		
		try {
			List list = new ArrayList<>();
			for (String  key : params.values()) {
				list.add(key);
			}
			Object[] strArray = list.toArray();
//			 template.convertAndSend("/topic/service_Model",new OutMessage(JSON.toJSONString(strArray)));
			 template.convertAndSend("/topic/service_Model",strArray);
			 return ResultObj.PUBLISH_SUCCESS;
		} catch (Exception e) {
			 e.printStackTrace();
			 return ResultObj.PUBLISH_ERROR;
		}
	}
	
	/**
	 * 判断时间是否在时间段内
	 * 
	 * @param nowTime
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	public static boolean belongCalendar(Date nowTime, Date beginTime,
			Date endTime) {
		Calendar date = Calendar.getInstance();
		date.setTime(nowTime);
 
		Calendar begin = Calendar.getInstance();
		begin.setTime(beginTime);
 
		Calendar end = Calendar.getInstance();
		end.setTime(endTime);
 
		if (date.after(begin) && date.before(end)) {
			return true;
		} else {
			return false;
		}
	}
	
	
	
	/**
	 * 在指定的银行网点下，通过设备编号获取 业务引导数据
	 */
	@RequestMapping("/knowDataByterminalNo")
	@ResponseBody
	public ResponseWrapper knowDataByterminalNo(String terminal_no){
		QueryWrapper<Terminal> queryWrapper = new QueryWrapper<Terminal>();
		QueryWrapper<ServiceLead> queryWrapperSe = new QueryWrapper<ServiceLead>();
		
		try {
			queryWrapper.eq(StringUtils.isNotBlank(terminal_no), "terminal_no", terminal_no);
			Terminal terminal = this.terminalService.getOne(queryWrapper);
			//通过设备编号 获取 业务引导数据
			queryWrapperSe.eq(StringUtils.isNotBlank(terminal.getTerminalno()), "terminal_no", terminal.getTerminalno());
				List<ServiceLead> serviceLeadList = this.serviceLeadService.list(queryWrapperSe);
				return ResponseWrapper.markSuccess(serviceLeadList);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseWrapper.markParamError();
		}
	}
	
	/**
	 * 根据设备编号、展示 （个人、企业） 普惠业务数据
     *          展示（热门、个人推荐）普惠业务数据
	 */
	@RequestMapping("/inclusiveDataByterminalNo")
	@ResponseBody
	public ResponseWrapper inclusiveDataByterminalNo(String terminal_no){
		QueryWrapper<Terminal> queryWrapper=new QueryWrapper<>();
		QueryWrapper<InclusiveService> queryWrapperIn=new QueryWrapper<>();
		try {
			queryWrapper.eq(StringUtils.isNotBlank(terminal_no), "terminal_no", terminal_no);
			Terminal terminal = this.terminalService.getOne(queryWrapper);
			//通过设备编号 获取 普惠业务数据
			queryWrapperIn.eq(StringUtils.isNotBlank(terminal.getTerminalno()), "terminal_no", terminal.getTerminalno());
			List<InclusiveService> inclusiveServiceList = this.inclusiveServiceService.list(queryWrapperIn);
			return ResponseWrapper.markSuccess(inclusiveServiceList);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseWrapper.markParamError();
		}
	}
	
	/**
	 * 根据设备编号 获取该网点下的生活缴费列表
	 */
	@RequestMapping("/quaryLivePayDataByterminalNo")
	@ResponseBody
	public ResponseWrapper quaryLivePayDataByterminalNo(String terminal_no){
		QueryWrapper<Terminal> queryWrapper = new QueryWrapper<Terminal>();
		QueryWrapper<LivePay> queryWrapperSe = new QueryWrapper<LivePay>();
		try {
			queryWrapper.eq(StringUtils.isNotBlank(terminal_no), "terminal_no", terminal_no);
			Terminal terminal = this.terminalService.getOne(queryWrapper);
			//通过网点编号 获取 生活缴费列表
			queryWrapperSe.eq(terminal.getNetworkid()!= null, "banknbr", terminal.getNetworkid());
				List<LivePay> livePayList = this.livePayService.list(queryWrapperSe);
				return ResponseWrapper.markSuccess(livePayList);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseWrapper.markParamError();
		}
	}

	/**
	 * 根据设备编号 获取该网点下的周边优惠列表
	 */
	@RequestMapping("/quarySurroundDataByterminalNo")
	@ResponseBody
	public ResponseWrapper quarySurroundDataByterminalNo(String terminal_no){
		QueryWrapper<Terminal> queryWrapper = new QueryWrapper<Terminal>();
		QueryWrapper<SurroundDiscount> queryWrapperSe = new QueryWrapper<SurroundDiscount>();
		
		try {
			queryWrapper.eq(StringUtils.isNotBlank(terminal_no), "terminal_no", terminal_no);
			Terminal terminal = this.terminalService.getOne(queryWrapper);
			//通过网点编号 获取周边优惠列表
			queryWrapperSe.eq(terminal.getNetworkid()!= null, "banknbr", terminal.getNetworkid());
			List<SurroundDiscount> surroundDiscountList = this.surroundDiscountService.list(queryWrapperSe);
			return ResponseWrapper.markSuccess(surroundDiscountList);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseWrapper.markParamError();
		}
	}

	/**
	 * 根据设备编号 获取该网点下的屏保数据
	 */
	@RequestMapping("/quaryScreensByterminalNo")
	@ResponseBody
	public ResponseWrapper quaryScreensByterminalNo(String terminal_no){
		QueryWrapper<Terminal> queryWrapper = new QueryWrapper<Terminal>();
		QueryWrapper<Screens> queryWrapperSe = new QueryWrapper<Screens>();
		
		try {
			queryWrapper.eq(StringUtils.isNotBlank(terminal_no), "terminal_no", terminal_no);
			Terminal terminal = this.terminalService.getOne(queryWrapper);
			//通过网点编号 获取周边优惠列表
			queryWrapperSe.eq(terminal.getNetworkid()!= null, "banknbr", terminal.getNetworkid());
			List<Screens> screensList = this.screensService.list(queryWrapperSe);
			return ResponseWrapper.markSuccess(screensList);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseWrapper.markParamError();
		}
	}
	
	
	
	
	
	
	/**
	 * 跳转到登陆页面
	 */
	@RequestMapping("login")
	public String toLogin() {
		return "system/index/login";
	}
	
	/**
	 * 退出跳转到登陆页面
	 */
	@RequestMapping("logout")
	public String tologout(HttpServletRequest request) {
		Enumeration em = request.getSession().getAttributeNames();
		while(em.hasMoreElements()){
			request.getSession().removeAttribute(em.nextElement().toString());
		}
		return "system/index/login";
	}
	
	/**
	 * 跳转到首页
	 */
	@RequestMapping("index")
	public String index() {
		return "system/index/index";
	}
	
	/**
	 * 跳转到工作台
	 */
	@RequestMapping("toDeskManager")
	public String toDeskManager() {
		return "system/index/deskManager";
	}
	
	
}
